package com.seh.contentcenter.controller.es;

import com.seh.contentcenter.domain.JsonResult;
import com.seh.contentcenter.dto.GoodsDTO;
import com.seh.contentcenter.entity.Goods;
import com.seh.contentcenter.es.ESGoods;
import com.seh.contentcenter.service.es.ESGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/esGoods")
public class ESGoodsController {
    @Autowired
    private ESGoodsService esGoodsService;

    @Autowired
    private RedisTemplate<String, Object> objectRedisTemplate;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Value("${file-save-path}")
    private String fileSavePath;

    /**
     * 添加二手商品
     * @param ESGoods
     * @param files
     * @param request
     * @return
     */
    @PostMapping("/addGoods")
    public Map<String, String> addGoods(Goods ESGoods,
                                        @RequestParam("files") MultipartFile[] files,
                                        HttpServletRequest request) {
        for (MultipartFile file : files) {
            //1.后半段目录：  2020-03-15
            String directory = simpleDateFormat.format(new Date());
            /**
             *  2.文件保存目录  E:/images/2020/03/15/
             *  如果目录不存在，则创建
             */
            File dir = new File(fileSavePath + directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            log.info("es商品图片上传，保存位置：" + fileSavePath + directory);
            //3.给文件重新设置一个名字
            //后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            //4.创建这个新文件
            File newFile = new File(fileSavePath + directory + "/" + newFileName);
            //5.复制操作
            try {
                file.transferTo(newFile);
                //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/picture_test/" + directory + "/" + newFileName;
                if (ESGoods.getGoodsPic() != null) {
                    String picPath = ESGoods.getGoodsPic();
                    ESGoods.setGoodsPic(picPath + ";" + url);
                } else {
                    ESGoods.setGoodsPic(url);
                }
            } catch (IOException e) {
                JsonResult result = JsonResult.builder().data(null).message("IO异常！").code("-1").build();
            }
        }
        GoodsDTO goodsDTO = new GoodsDTO();
        BeanUtils.copyProperties(ESGoods, goodsDTO);
        goodsDTO.setGoodsStatus(0);
        goodsDTO.setIsDel(0);
        esGoodsService.addGoods(goodsDTO);
        Map<String, String> map = new HashMap<>();
        map.put("msg", "ok");
        objectRedisTemplate.delete("goods");//每新增一个商品就清空一次缓存
        return map;
    }

    /**
     * 使用的时候必须添加 key = #{value}，否则查不到商品
     * @param key
     * @return
     */
    @GetMapping("/search")
    public List<ESGoods> search(String key) {
        return esGoodsService.search(key);
    }

    /**
     * 使用的时候必须添加 key = #{value}，否则查不到商品
     * @param key
     * @return
     */
    @GetMapping("/searchHits")
    public SearchHits<ESGoods> searchHits(String key) {
        return esGoodsService.searchGoods(key);
    }

    @GetMapping("/deleteGoods/{id}")
    public void deleteGoods(@PathVariable String id) {
        esGoodsService.deleteGoods(id);
    }
}
